package com.wngbms.fileio.sharemem;

import java.nio.charset.StandardCharsets;

public class ShareMemWrite {

    public static void main(String[] args) {
        ShareMemory shareMemory = new ShareMemory();

//        m1(shareMemory);

        for (int i = 0; i < 100; i++) {
            String s = Thread.currentThread().getName() + "小米手机就是好用 Windows 11 Sony Apple " + i + "\r\n";
            byte[] bytes = s.getBytes(StandardCharsets.UTF_8);

            int write = shareMemory.write(0, bytes.length, bytes);
            System.out.print("write:"+ write + "\t"  + s);

            sleep(800);
        }

    }

    private static void m1(ShareMemory shareMemory) {
        Runnable runnable = () -> {
            String s = Thread.currentThread().getName() + "小米手机就是好用 Windows 11 Sony Apple " + 0 + "\r\n";
            byte[] bytes = s.getBytes(StandardCharsets.UTF_8);

            for (int i = 0, pos = 0, ret = 0; ret != -1; i++, pos = pos += bytes.length) {
                ret = shareMemory.write(pos, bytes.length, bytes);
                System.out.print("write:" + new String(bytes, StandardCharsets.UTF_8));
                sleep(10);
            }

            shareMemory.close();

        };
        new Thread(runnable, "t1").start();
        new Thread(runnable, "t2").start();
    }


    public static void sleep(long t) {
        try {
            Thread.sleep(t);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
